import {
  USER_INFO,
  TOKEN,
  MATERIAL_HISTORY,
  PRODUCT_HISTORY,
  IS_LOGIN
} from '@/common/utils/cachekey.js';
import Cache from '@/common/utils/cache'
import util from '@/common/utils/index.js'

const state = {
  token: Cache.get(TOKEN) || '',
  userInfo: Cache.get(USER_INFO) || null,
  materialHistory: Cache.get(MATERIAL_HISTORY) || [],
  productHistory: Cache.get(PRODUCT_HISTORY) || [],
  isLogin: Cache.get(IS_LOGIN) || false
};

const mutations = {
  login(state, data) {
		state.isLogin = true
		Cache.set(IS_LOGIN, true)
    state.token = data.token
    state.userInfo = data.userInfo
    Cache.set(USER_INFO, data.userInfo)
    Cache.set(TOKEN, data.token)
  },
	setToken(state, data) {
		state.token = data.token
		Cache.set(TOKEN, data.token)
	},
  logout(state) {
    state.isLogin = false
    Cache.set(IS_LOGIN, false)
    state.userInfo = null
    state.token = ''
    Cache.remove(USER_INFO)
    Cache.remove(TOKEN)
		uni.reLaunch({
			url: '/pages/index/index'
		})
  },
  setUserInfo(state, data) {
    state.userInfo = data
    Cache.set(USER_INFO, data)
  },
  setMaterialHistory(state, data) {
    state.materialHistory = data
    Cache.set(MATERIAL_HISTORY, data)
  },
  setProductHistory(state, data) {
    state.productHistory = data
    Cache.set(PRODUCT_HISTORY, data)
  }
};

const actions = {
  login({state, commit}, data) {
    commit('login', data)
  },
	setToken({state, commit}, data) {
    commit('setToken', data)
  },
  setUserInfo({state, commit}, userInfo) {
    commit('setUserInfo', userInfo)
  },
  logout({state, commit}) {
    commit('logout')
  },
  setMaterialHistory({state, commit}, keyword) {
    if (!keyword) return
    let list = JSON.parse(JSON.stringify(state.materialHistory || [])) || []
    if (!list.includes(keyword)) {
      list.unshift(keyword)
      commit('setMaterialHistory', list)
    }
  },
  setProductHistory({state, commit}, keyword) {
    if (!keyword) return
    let list = JSON.parse(JSON.stringify(state.productHistory || [])) || []
    if (!list.includes(keyword)) {
      list.unshift(keyword)
      commit('setProductHistory', list)
    }
  },
  clearHistory({state, commit}, type) {
    if (type == 'xuancai') {
      commit('setMaterialHistory', [])
    } else {
      commit('setProductHistory', [])
    }
  }
};

export default {
  state,
  mutations,
  actions
};
